﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using AmuTools;
using app.Api;

namespace app.Models
{
    /// <summary>
    /// 数据字典类
    /// </summary>
    [Model(TableName = "t_datadictionary", PrimaryKey = "id", IdentityInsert = false)]
    public partial class DataDictionary
    {
        public int id { get; set; }
        public int parent_id { get; set; }//形成树形结构所需要的父结点ID
        public string dictype { get; set; } //数据字典的类型
        public string name { get; set; }
        public string logo_ids { get; set; }
        private List<UploadedFile> _logo = null;
        [Field(Storageable = false)]
        public List<UploadedFile> logo //返回前端的图片属性,不可存入数据库
        {
            get
            {
                if (logo_ids == ""||logo_ids == null) { _logo = new List<UploadedFile>(); }
                else { _logo = G.DB.Get<UploadedFile>(string.Format("{0} in ({1})", G.DB.GetPrimaryKey<UploadedFile>(), logo_ids)).GetFirstTableList<UploadedFile>(); }
                return _logo;
            }
        }
        public string url { get; set; }//链接地址
        public string remark { get; set; }//备注
        [Field(DataType = "char(13)")]
        public string create_time { get; set; }
        public int is_visible { get; set; }//该项数据字典是否可见
        
        //创建数据字典的缓存变量
        private static Dictionary<string, Dictionary<string, object>> cacheDicTree = null;
        //更新缓存函数
        public static Dictionary<string, Dictionary<string, object>> GetCache()
        {
            if(cacheDicTree == null)
            {
                cacheDicTree = ListToTree(G.DB.Get<DataDictionary>(0).GetFirstTableList<DataDictionary>());
            }
            return cacheDicTree;
        }
        //删除一个节点
        public static int RemoveNode(int id)
        {
            // 删除自己
            G.DB.Delete<DataDictionary>(id);

            // 拿到所有儿子
            List<DataDictionary> list = G.DB.Get<DataDictionary>(string.Format("parent_id={0}", id)).GetFirstTableList<DataDictionary>();

            // 删除儿子
            foreach(DataDictionary item in list)
            {
                RemoveNode(item.id);
            }
            cacheDicTree = null;
            GetCache();
            return 0;
        }
        //添加节点，返回ID
        public static void AddNode(DataDictionary obj)
        {
            G.DB.Insert<DataDictionary>(obj);
            cacheDicTree = null;
            GetCache();
        }
        public static int UpdataNode(DataDictionary obj)
        {
            int i = G.DB.Update<DataDictionary>(obj);
            cacheDicTree = null;
            GetCache();
            return i;
        }
        //将查询到的列表转化成树形结构
        public static Dictionary<string, Dictionary<string, object>> ListToTree(List<DataDictionary> list)
        {
            // 将DataDictionary列表转为Dictionary<string, object>列表
            List<Dictionary<string, object>> dic_list = new List<Dictionary<string, object>>();
            foreach (DataDictionary item in list)
            {
                Dictionary<string, object> temp = CreateNode(item.id, item.parent_id, item.dictype, item.name, item.create_time, null, item.logo_ids,item.logo ,item.url, item.remark, item.is_visible);
                temp.Add("parent", null);
                dic_list.Add(temp);
            }
            foreach (Dictionary<string, object> item in dic_list)
            {
                foreach(Dictionary<string, object> item2 in dic_list)
                {
                    if (item == item2) continue;
                    // 判断item是不是item2的子集
                    if( item["parent"] == null && item["parent_id"].ToString() == item2["id"].ToString())
                    {
                        item["parent"] = item2;
                        ((List<Dictionary<string, object>>)item2["children"]).Add(item);
                    }
                }
            }
            //最终打包整理完毕要发送的数据
            Dictionary<string, Dictionary<string, object>> allSendDic = new Dictionary<string, Dictionary<string, object>>();
            List < Dictionary < string, object>> t = new List<Dictionary<string, object>>();
            allSendDic.Add("area", CreateNode(0, 0, "area", "地区"));
            allSendDic.Add("notice", CreateNode(0, 0, "notice", "通知公告"));
            allSendDic.Add("news", CreateNode(0, 0, "news", "新闻资讯"));
            allSendDic.Add("laws", CreateNode(0, 0, "laws", "政策法规"));
            allSendDic.Add("service", CreateNode(0, 0, "service", "服务类别"));
            allSendDic.Add("demand", CreateNode(0, 0, "demand", "需求类别"));
            allSendDic.Add("service_agency", CreateNode(0, 0, "service_agency", "服务机构类别"));
            allSendDic.Add("industry", CreateNode(0, 0, "industry", "行业类别"));
            allSendDic.Add("company_type", CreateNode(0, 0, "company_type", "企业类别"));
            allSendDic.Add("usual_service", CreateNode(0, 0, "usual_service", "专项服务"));
            allSendDic.Add("friendly_link", CreateNode(0, 0, "friendly_link", "友情链接"));
            allSendDic.Add("help", CreateNode(0, 0, "help", "帮助中心"));
            allSendDic.Add("index_logo", CreateNode(0, 0, "index_logo", "网站logo"));
            allSendDic.Add("index_carousel", CreateNode(0, 0, "index_carousel", "首页轮播图"));
            allSendDic.Add("mid_carousel", CreateNode(0, 0, "mid_carousel", "中部轮播图"));
            allSendDic.Add("subpage_image", CreateNode(0, 0, "subpage_image", "子页背景图"));
            allSendDic.Add("ad_image", CreateNode(0, 0, "ad_image", "广告位"));
            allSendDic.Add("browser", CreateNode(0, 0, "browser", "浏览器"));
            allSendDic.Add("file_submit_type", CreateNode(0, 0, "file_submit_type", "材料文件类别"));
            // 找到所有无根节点，添加到跟节点上
            foreach (Dictionary<string, object> item in dic_list)
            {
                if (item["parent"] == null)
                {
                    string dictype = item["dictype"].ToString();
                    if (!allSendDic.ContainsKey(dictype))
                    {
                        allSendDic.Add(dictype, CreateNode(0, 0, dictype, dictype));
                    }
                    ((List<Dictionary<string, object>>)allSendDic[dictype]["children"]).Add(item);
                }
                item.Remove("parent");
            }

            return allSendDic;
        }

        private static Dictionary<string, object> CreateNode(int id, int parent_id, string dictype, string name, string create_time = "0000000000000",
          List<Dictionary<string, object>>  children = null, string logo_ids = "",List<UploadedFile> logo = null, string url = "", string remark = "", int is_visible = 1)
        {
            Dictionary<string, object> node = new Dictionary<string, object>();
            node.Add("id", id);
            node.Add("parent_id", parent_id);
            node.Add("dictype", dictype);
            node.Add("name", name);
            node.Add("create_time", create_time);
            node.Add("children", children == null ? new List<Dictionary<string, object>>() : children);
            node.Add("logo", logo);
            node.Add("url", url);
            node.Add("remark", remark);
            node.Add("logo_ids", logo_ids);
            node.Add("is_visible", is_visible);
            return node;
        }
    }
}